<template>
  <div class="care">
    <Button type="primary" :disabled="disabled" @click="visible = true">{{
      text
    }}</Button>
    <el-dialog
      :visible.sync="visible"
      :close-on-click-modal="false"
      :title="title"
      :append-to-body="true"
      @open="openSinga"
      @close="resetForm"
    >
      <div class="content">
        <FormContainer :column="2" :disabled="preview">
          <el-form
            ref="form"
            :model="formData"
            :rules="formRules"
            label-width="80px"
          >
            <el-form-item label="关怀对象" prop="careObject">
              <el-input v-model.trim="formData.careObject" placeholder="请输入关怀对象" clearable></el-input>
            </el-form-item>
            <el-form-item label="电话" prop="careObjectPhone">
              <el-input v-model.trim="formData.careObjectPhone" placeholder="请输入电话" number clearable></el-input>
            </el-form-item>
            <!-- <el-form-item label="收货地址" prop="province">
              <Address v-model="formData.province" :name.sync="formData.provinceName" label="省" init placeholder="请选择省" clearable filterable></Address>
            </el-form-item>
            <el-form-item prop="city" label="市">
              <Address v-model="formData.city" :name.sync="formData.cityName" :parent="formData.province" placeholder="请选择市" clearable filterable></Address>
            </el-form-item>
            <el-form-item prop="county" label="区/县">
              <Address v-model="formData.county" :name.sync="formData.countyName" :parent="formData.city" placeholder="请选择区" clearable filterable></Address>
            </el-form-item>
            <el-form-item prop="street" label="街道">
              <Address v-model="formData.street" :name.sync="formData.streetName" :parent="formData.county" placeholder="请选择街道" clearable filterable></Address>
            </el-form-item>
            <el-form-item label="详细地址" :span="24">
              <el-input v-model="formData.detailAddress" type="textarea" placeholder="请输入详细地址" :autosize="{minRows:1}"></el-input>
            </el-form-item> -->
            <el-form-item label="收货地址" :span="24">
              <el-input v-model="formData.detailAddress" type="textarea" placeholder="请输入详细地址" :autosize="{minRows:1}"></el-input>
            </el-form-item>
            <el-form-item prop="careMode" label="关怀方式" :span="24">
              <CustomDictSelect
                placeholder="请选择关怀方式"
                dict-type-code="CARE_MODE"
                bind-name="dictName"
                bind-value="dictCode"
                multiple
                :echo-value.sync="formData.careMode"
                :echo-name.sync="formData.careModeName"
                clearable
              ></CustomDictSelect>
            </el-form-item>
            <template v-if="formData.careMode.includes('4')||formData.careMode.includes(4)">
              <template v-for="(item, index) in formData.careTaskGiftList">
                <el-form-item
                  :key="index"
                  :prop="'careTaskGiftList.' + index + '.product'"
                  label="礼品名称"
                  :span="24/3"
                >
                  <SearchSelectPicker
                    url="/call-center/api/v1/careGift/page"
                    placeholder="请选择礼品"
                    lable-name="giftName"
                    value-name="giftCode"
                    :value.sync="item.giftCode"
                    :lable.sync="item.giftName"
                    :current-id.sync="item.giftId"
                  ></SearchSelectPicker>
                </el-form-item>
                <el-form-item
                  :key="index + 'num'"
                  :span="24/3"
                  :prop="'careTaskGiftList.' + index + '.quantity'"
                  label="礼品数量"
                >
                  <el-select
                    v-model="item.quantity"
                    placeholder="请选择"
                    filterable
                    clearable
                  >
                    <el-option
                      v-for="(list, key) in 5"
                      :key="key"
                      :label="list"
                      :value="list"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item :key="index + 'svg'" :span="24/3">
                  <svg
                    v-if="index === formData.careTaskGiftList.length-1"
                    class="icon"
                    aria-hidden="true"
                    @click="addItem"
                  >
                    <use xlink:href="#tianjiaxinjian" />
                  </svg>
                  <svg
                    v-if="formData.careTaskGiftList.length!==1"
                    class="icon delete"
                    aria-hidden="true"
                    @click="deleteItem(item, index)"
                  >
                    <use xlink:href="#shanchulajixiang-line" />
                  </svg>
                </el-form-item>
              </template>
            </template>
            <!-- <el-form-item prop="handler" label="分配坐席">
              <StaffSearch v-model="formData.handler" :name.sync="formData.handlerName" placeholder="请选择分配坐席" clearable></StaffSearch>
            </el-form-item> -->
            <el-form-item prop="agreedCareDate" label="预约关怀日期">
              <el-date-picker
                v-model="formData.agreedCareDate"
                type="date"
                placeholder="选择预约关怀日期"
                value-format="yyyy-MM-dd"
                operator="<"
                :limite="new Date()"
              />
            </el-form-item>
            <el-form-item prop="remarks" label="备注" :span="24">
              <el-input
                v-model="formData.remarks"
                type="textarea"
                :autosize="{ minRows: 3 }"
                placeholder="请输入备注"
                clearable
                :maxlength="150"
                tip
              />
            </el-form-item>
            <el-form-item v-if="!preview" label="" align="right" :span="24">
              <Button @click="visible = false">取消</Button>
              <Button type="primary" @click="submitHandle">确定</Button>
            </el-form-item>
          </el-form>
        </FormContainer>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Button from '@/components/Button'
import FormContainer from '@/components/FormContainer'
import SearchSelectPicker from '@/components/SearchSelectPicker'
import { deepCopy } from '@/utils/'
import { postConsumerCareTask, careTaskDetail } from '@/api/guestCare'
// import StaffSearch from '@/components/StaffSearch'
// import Address from '@/components/Address'
import CustomDictSelect from '@/components/CustomDictSelect'
import { mapGetters } from 'vuex'
import { getWinningDetail } from '@/api/serviceQuality'
export default {
  name: 'Care',
  components: {
    Button,
    SearchSelectPicker,
    FormContainer,
    // Address,
    CustomDictSelect
    // StaffSearch
  },
  props: {
    disabled: {
      type: Boolean,
      default: false
    },
    text: {
      type: String,
      default: ''
    },
    title: {
      type: String,
      default: ''
    },
    row: {
      type: Object,
      default: () => {
        return {}
      }
    },
    preview: {
      type: Boolean,
      default: false
    }
  },
  data() {
    // 验证关怀方式
    const validatorCareMode = (r, v, c) => {
      if (v instanceof Array && v.length > 0) {
        c()
      } else {
        c(new Error('请选择关怀方式'))
      }
    }
    return {
      visible: false,
      formData: {
        // 新增
        careObject: '',
        careObjectPhone: '',
        province: '',
        provinceName: '',
        city: '',
        cityName: '',
        county: '',
        countyName: '',
        street: '',
        streetName: '',
        detailAddress: '',
        careMode: [],
        careModeName: '',
        agreedCareDate: '',
        careTaskGiftList: [],
        remarks: '',
        disCode: '',
        disName: '',
        officeCode: '',
        officeName: '',
        shopCode: '',
        shopName: '',
        // 额外信息
        winningCode: '',
        handler: '',
        handlerName: '',
        careItem: 7,
        careItemName: '中奖顾客'
      },
      formRules: {
        careObject: [{ required: true, message: '请输入关怀对象', trigger: 'change' }],
        careObjectPhone: [{ required: true, message: '请输入电话', trigger: 'change' }],
        careTaskGiftList: [{ required: true, trigger: 'change' }],
        careMode: [{ required: true, message: '请选择关怀方式', trigger: 'change' },
          { validator: validatorCareMode, trigger: 'change' }],
        handler: [{ required: true, message: '请选择分配坐席', trigger: 'change' }]
      },
      careTypeOp: [],
      detail: {}
    }
  },
  computed: {
    ...mapGetters(['staffName', 'accountNo'])
  },
  watch: {
    'formData.careMode'(v) {
      if (v.includes('4') || v.includes(4)) {
        if (this.formData.careTaskGiftList.length <= 0) {
          this.addItem()
        }
      }
    }
  },
  created() {

  },
  methods: {
    // 检查礼物数据
    checkGift() {
      if (this.formData.careMode.includes('4') || this.formData.careMode.includes(4)) {
        for (const item of this.formData.careTaskGiftList) {
          for (const value of Object.values(item)) {
            if (value === '') {
              this.$message.error('请完整填写礼品数据！')
              return false
            }
          }
        }
        return true
      }
      return true
    },
    // 增加表单Item
    addItem() {
      this.formData.careTaskGiftList.push({ giftCode: '', giftId: '', giftName: '', quantity: '' })
    },
    // 删除动态Item
    deleteItem(item, index) {
      this.formData.careTaskGiftList.splice(index, 1)
    },
    // 关闭弹窗
    openSinga() {
      if (this.preview) {
        this.previewHandle()
      }
      // 客户信息
      const set = (key, vKey) => {
        let v = this.row[vKey]
        if (v === undefined || v === null) {
          v = ''
        }
        this.$set(this.formData, key, v)
      }
      set('careObject', 'customerName')
      set('careObjectPhone', 'customerPhone')
      // 地址信息
      set('province', 'province')
      set('city', 'city')
      set('county', 'county')
      set('street', 'street')
      set('provinceName', 'provinceName')
      set('cityName', 'cityName')
      set('countyName', 'countyName')
      set('streetName', 'streetName')
      set('detailAddress', 'address')
      // ====== 将地址选择器改为文本=====
      this.$set(this.formData, 'detailAddress', `${this.row['provinceName'] || ''}${this.row['cityName'] || ''}${this.row['countyName'] || ''}${this.row['streetName'] || ''}${this.row['address'] || ''}`)
      // ==============================
      set('winningCode', 'winningCode')
      // 办事处等
      set('disCode', 'disCode')
      set('disName', 'disName')
      set('officeCode', 'officeCode')
      set('officeName', 'officeName')
      set('shopCode', 'shopCode')
      set('shopName', 'shopName')
      // 默认坐席
      // this.$set(this.formData, 'handler', this.accountNo)
      // this.$set(this.formData, 'handlerName', this.staffName)
    },
    // 重置表单
    resetForm() {
      this.$refs.form.resetFields()
      this.formData.careMode = []
      this.formData.careTaskGiftList = []
    },
    // 确定
    submitHandle() {
      return this.$refs.form.validate().then(() => {
        if (!this.checkGift()) {
          return
        }
        const data = deepCopy(this.formData)
        if (!data.careMode.includes('4') && !data.careMode.includes(4)) {
          delete data.careTaskGiftList
        }
        data.careMode = data.careMode.join(',')
        return postConsumerCareTask(data).then(res => {
          if (res.success === 1) {
            this.$message({
              message: '关怀任务生成成功',
              type: 'success'
            })
            this.$emit('on-success', true)
            this.visible = false
          }
        })
      })
    },
    // 查看获取
    previewHandle() {
      getWinningDetail(this.row.winningCode).then(d => {
        return careTaskDetail(d.id).then(res => {
          this.detail = res.data
          for (const k of Object.keys(this.formData)) {
            const v = this.detail[k]
            if (k === 'careMode' && v) {
              this.$set(this.formData, k, v.split(','))
            } else {
              this.$set(this.formData, k, v)
            }
          }
        })
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.care {
  display: inline-block;
  & .content {
    padding: 0;
  }
}
.icon {
  width: 1.3em;
  height: 1.3em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
  color: #16bc83;
  cursor: pointer;
  margin: 5px;
}
.delete {
  color: red !important;
}
</style>
